package com.xing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.dao.LiveRoomDao;
import com.xing.dao.LiveRoomTagDao;
import com.xing.dto.LiveTagDTO;
import com.xing.entity.LiveRoomEntity;
import com.xing.entity.LiveRoomTagEntity;
import com.xing.service.LiveRoomTagService;
import com.xing.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class LiveRoomTagServiceImpl extends ServiceImpl<LiveRoomTagDao, LiveRoomTagEntity> implements LiveRoomTagService {

    @Autowired
    private LiveRoomTagDao roomTagDao;
    @Autowired
    private LiveRoomDao liveRoomDao;


    @Override
    public List<String> getRoomTagByRoomId(Long roomId) {
        return roomTagDao.getRoomTagByRoomId(roomId);
    }

    @Override
    public List<LiveTagDTO> getRoomTagByRoomDTOId(Long roomId) {
        return roomTagDao.getRoomTagEntityByRoomId(roomId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    public void updateRoomTag(List<LiveTagDTO> list) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        QueryWrapper<LiveRoomEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("anchor_id",principal.getId());
        LiveRoomEntity roomEntity = liveRoomDao.selectOne(wrapper);
        roomTagDao.deleteByAnchorId(principal.getId());
        List<LiveRoomTagEntity> liveTags = new ArrayList<>();
        for (LiveTagDTO liveTagDTO : list) {
            LiveRoomTagEntity liveRoomTagEntity = new LiveRoomTagEntity();
            liveRoomTagEntity.setRoomId(roomEntity.getId());
            liveRoomTagEntity.setTagId(liveTagDTO.getId());
            liveTags.add(liveRoomTagEntity);
        }
        boolean b = saveBatch(liveTags);
    }
}
